using UnityEngine;
using System.Collections;

public class Missions : MonoBehaviour {

	public tk2dTextMesh[] objetivos;
	public tk2dTextMesh[] effect;
	string[] others = new string[10];
	bool switchObj;
	float timer;
	int indexObj;
	bool isLoading;
	string sceneName;
	
	void Awake()
	{

	}
	
	void Update () 
	{
		if(switchObj)
		{
			timer += Time.deltaTime;
			Debug.Log(timer);
			if(timer > 1.6)
			{
				foreach(tk2dTextMesh texts in effect)
				{
					texts.text = "";
					texts.Commit();
				}
				for(int i = indexObj; i < 3;i++)
				{
					if(objetivos[indexObj + 1] != null)
					{
						objetivos[indexObj].text = objetivos[indexObj + 1].text;
						objetivos[indexObj].Commit();
					}
				}
				objetivos[2].text = "- ";
				objetivos[2].Commit();
				
				if(others[0] != null)
				{
					foreach (tk2dTextMesh texts in objetivos)
					{
						if(texts.text == "- ")
						{
							for (int i = 0; i < 10; i++) 
							{
								if(others[i] != "")
								{
									texts.text = others[i];
									texts.Commit();
									break;
								}
							}
						}	
					}
				}
				if(isLoading)
				{
					changeScene(sceneName);
				}
				timer = 0;
				switchObj = false;
			}
		}
			
	}
	
	public void AddMission(string text)
	{
		for (int i = 0; i < objetivos.Length; i++) 
		{
			if(objetivos[i].text == "- ")
			{
				objetivos[i].text = text;
				objetivos[i].Commit();
				break;
			}
		}
			
		if(objetivos[2].text != "- ")
		{
			for (int i = 0; i < 10; i++) 
			{
				if(others[i] == "")
				{
					others[i] = text;
					break;
				}	
			}
		}
	}
	
	public void RemoveMission(int index)
	{
		for (int i = 0; i < 10; i++) 
		{
			if(effect[index] != null)
			effect[index].text += "_";
		}
		
		effect[index].Commit();
		indexObj = index;
		switchObj = true;
	}
	public void newLoading(string scene)
	{
		sceneName = scene;
		isLoading = true;
	}
	
	void changeScene(string scene)
	{
		for (int i = 0; i < 3; i++) 
		{
			PlayerPrefs.SetString("objetivos"+i,objetivos[i].text);	
		}
		
		Application.LoadLevel(scene);
	}
	
	public int returnIndex(string text)
	{
		int count = 0;
		
		foreach(tk2dTextMesh texts in objetivos)
		{
			if(texts.text == text)
			{
				break;
			}
			count ++;
		}
		
		return count;
	}
}
